package free.play.controller;

import free.play.model.request.CreateCustomerRequest;
import free.play.validation.BindingResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Locale;
import javax.validation.Valid;

@Controller
@RequestMapping("customer")
public class CustomerController {

  @Autowired
  private MessageSource messageSource;

  @RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
  public ResponseEntity createCustomer(
      @RequestBody @Valid CreateCustomerRequest createCustomerRequest, BindingResult result,
      Locale locale) {

    for (ObjectError err : result.getAllErrors()) {
      String msg = messageSource.getMessage(err, locale);
      System.out.println(msg);
    }
    if (result.hasErrors()) {
      return ResponseEntity.badRequest().body(BindingResultUtils.toErrorCodes(result));
    }
    return ResponseEntity.ok().build();
  }

}
